package com.shenmazong.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenmazong.user.pojo.TbAdmin;
import com.shenmazong.user.pojo.TbUser;
import com.shenmazong.user.service.TbUserService;
import com.shenmazong.user.mapper.TbUserMapper;
import com.shenmazong.utils.ResultResponse;
import com.shenmazong.utils.TokenUtils;
import com.shenmazong.vo.IdVo;
import com.shenmazong.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public ResultResponse get(IdVo idVo) {
        //--1 获取用户
        TbUser tbUser = tbUserMapper.selectById(idVo.getId());
        if(tbUser == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //--2 脱敏
        tbUser.setUserPass(null);

        //--3 用户信息
        return ResultResponse.SUCCESS(tbUser);
    }

    @Override
    public ResultResponse login(LoginVo loginVo) {
        //--1 检查是否存在
        TbUser one = tbUserMapper.selectOne(
                new QueryWrapper<TbUser>().lambda().eq(TbUser::getUserName, loginVo.getUserName()).last("limit 1")
        );
        if(one == null) {
            return ResultResponse.FAILED(404, "用户不存在");
        }

        //--2 校验密码
        boolean checkpw = BCrypt.checkpw(loginVo.getUserPass(), one.getUserPass());
        if(!checkpw) {
            return ResultResponse.FAILED(403, "用户密码不正确");
        }

        //--3 生成token
        String token = TokenUtils.token()
                .setKey("123456")
                .setExpire(60 * 30)
                .setClaim("userId", "" + one.getUserId())
                .setClaim("userName", one.getUserName())
                .makeToken();
        redisTemplate.opsForValue().set(token, token, 30, TimeUnit.MINUTES);

        //--4 返回用户信息
        one.setToken(token);

        //--5 脱密
        one.setUserPass(null);

        return ResultResponse.SUCCESS(one);
    }
}




